<script setup>
/**
 * @name 图文剪辑
*/
import { ref, reactive, onMounted, onUnmounted, watch, nextTick, computed, createVNode } from 'vue';

// 拖拽
import Draggable from "vuedraggable";

// 图文混剪工具方法
import GTC_tools from '@/views/shotstack/utils/helper.js'

// 可编辑头部
import EditableHead from "@/views/shotstack/MuseMixedCut/components/EditableHead.vue";
import {
    ExclamationCircleOutlined,
  HolderOutlined,
  LoadingOutlined
} from "@ant-design/icons-vue";


// 头部组件
import GraphicTextCutNavBack from './Components/GraphicTextCutNavBack.vue'
const GraphicTextCutNavBackRef = ref()


// 右侧 swiper组件
import ViewSwiper from './Components/ViewSwiper.vue'
const ViewSwiperRef = ref()

// 左侧列表组件
import GraphicTextCardList from './Components/GraphicTextCardList.vue'

import { useRouter, useRoute } from 'vue-router'; 
const router = useRouter();
const route = useRoute();
import { useStore } from "vuex";
import { message, Modal } from 'ant-design-vue';
const store = useStore();

import request from "@/common/utils/request";



// 仓库中的图文剪辑数据 
const GraphicTextMixCutData = computed(() => {
    return store.state.GraphicTextMixCut.GraphicTextMixCutData;
});

// 同步存储数据
const commit = () => {
    store.commit('GraphicTextMixCut/INIT_GRAPHICTEXT_DATA', GraphicTextMixCutData.value)
}

const state = reactive({
  // 是否预览中
  previewIng: false,

  // 是否加载中
  is_loading: false,

  // 提交按钮 loading
  submit_loading:false
})

const title = computed({
    get() {
        return GraphicTextMixCutData.value?.title
    },
    set(val) {
        GraphicTextMixCutData.value.title = val
        commit()
    }
})

// 加载失败
const initErr = (params={}) => {
  const {msg} = params
  Modal.confirm({
      content: msg || '加载失败!',
      cancelText: '返回',
      okText:'重试',
      centered:true,
      onOk() {
        location.reload()
      },
      onCancel() {
        router.back(1)
      },
    });
}

const getDetile = async (id) => {
  state.is_loading = true

  try {
    const res = await request.get(
        "/work_ai",
      "/user/image/clip/detail",{id}
    );
    console.log(res, '详情数据????');
    // throw new Error('加载失败')
    if(res?.code && res?.code != 1000) throw new Error('加载失败')
    const data = {
      resource_data: res.result.resource_data,
      id: res.result.id,
      title: res.result.title
    }
    store.commit('GraphicTextMixCut/INIT_GRAPHICTEXT_DATA', data)
    
  } catch (error) {
    initErr({msg:'获取详情失败!'})
  } finally {
    setTimeout(() => {
      state.is_loading = false
    },500)
  }
}

const initFn = async () => {
  try {
    await Promise.all([
      store.dispatch('GraphicTextMixCut/getFontList'),
      store.dispatch('GraphicTextMixCut/getFlowerListData'),
    ])

    const id = route.query?.detailId

    // 查询详情 回显数据
    if (id) {
      getDetile(id)
      return
    }

    // 初始化 创建数据
    const data = GTC_tools.getBaseGraphicText()
    console.log(data,'基础数据');
    store.commit('GraphicTextMixCut/INIT_GRAPHICTEXT_DATA', data)
  } catch (error) {
    console.log(error);
    initErr({msg:'获取基础数据失败!'})
    // message.error('初始化失败')
  }
}

onMounted(() => {
  initFn()
})

// 修改某组的名称
const updateName = (ev, element) => {
    element.name = ev;
    commit()
}

// 删除某组数据
const deletItemData = (index) =>{
    GraphicTextMixCutData.value.resource_data.splice(index, 1)
    commit()
}

// 新增镜头组
const addVideoGroupHandle = async () => {
      const list = GraphicTextMixCutData.value.resource_data;
      if (list.length < GTC_tools.GraphicTextCut_maxLength) {
        const data = GTC_tools.getResourceData({name:`场景${list.length}`});
        list.push(data);
        commit()
        nextTick(() => {
          GTC_tools.scrollToBottom('.videoGroupCard_box');
        });
      } else {
        return message.error(`最多只能添加${GTC_tools.GraphicTextCut_maxLength}个镜头组`);
      }
};

// 离开前的询问
const backClick = () => {
    Modal.confirm({
    title: "提示",
    icon: createVNode(ExclamationCircleOutlined),
    content: "当前页配置还未进行保存，直接离开数据不会保存和更新",
    cancelText: "确认返回",
    okText: "留在当前页",
        onCancel() {
        // 返回图文剪辑雷列表
        router.push({
          name: "GraphicTextCutList",
        });
    },
    });
};

// 提交 预览前的校验
const submitValidate = () => {
  return new Promise((resolve, reject) => {
    console.log(GraphicTextMixCutData.value, 'GraphicTextMixCutData.value');
    const resource_data = GraphicTextMixCutData.value.resource_data
    // 判断是否有空素材的项
    const haveImgEmpty = resource_data.some(ele => {
      const isempty = !(Array.isArray(ele.images) && ele.images.length)
      return isempty
    })
    if (haveImgEmpty) {
      console.log('有空值-----------');
      message.error('图片素材必填')
      reject(new Error('图片素材必填'))
      return
    }

    // 判断每个场景的图片素材 是否足够
    const imgTemplateList = GTC_tools.getGraphicImgTemplate()

    const isFind = resource_data.find(ele => {
      // 这组选择的模板 所需要的图片数量
      const needImgLength = imgTemplateList.find(item => item.value == ele.image_tpl)?.minNum
      const isInsufficient = ele.images.length < needImgLength
      return isInsufficient
    })

    if (isFind) {
      const needImgLength = imgTemplateList.find(item => item.value == isFind.image_tpl)?.minNum
      const msg = `${isFind.name}图片数量不够，至少上传${needImgLength}张图片`
      message.error(msg)
      reject(new Error(msg))
      return
    }
      
    resolve('ok')
  })
}

// 用户点击预览
const toPreview = async() => {
    await submitValidate()
  state.previewIng = true
}

// 清空预览效果
watch(() => GraphicTextMixCutData.value, (ov, nv) => {
  // 停止预览状态
  console.log(ov, nv,'变化了');
  
  state.previewIng && (state.previewIng = false)
}, {
  deep:true
})

// 仅保存
const handleSaveProject = async () => {
  state.submit_loading = true
  await submitValidate()

  try {
    const uniqueid = await request.get("/work_ai", "/user/platform/uniqueId")
    console.log(uniqueid, 'uniqueid');
    const data = GraphicTextMixCutData.value
    data.unique_id = uniqueid.uniqueId
    console.log(data,'参数??');
    
    // return
    const res = await request.post(
        "/work_ai",
      "/user/image/clip/save",data
    );
    console.log(res, '保存结果');
    
    // 异常了
    if (res?.code && res?.code != 1000) {
      message.error(res?.msg || '保存失败,请稍候重试!')
      throw new Error(res?.msg || '保存失败,请稍候重试!')
    }

    router.push({
      name: 'GraphicTextCutList',
    })
    
  } catch (error) {
  } finally {
    state.submit_loading = false
  }

}

// 剪辑预览
const previewHandle = async () => {
  
  // 校验数据
  await submitValidate()

  state.submit_loading = true

  try {
    // 获取唯一id 作为参数
    const uniqueid = await request.get("/work_ai", "/user/platform/uniqueId")
    console.log(uniqueid, 'uniqueid');
    const data = GraphicTextMixCutData.value
    data.unique_id = uniqueid.uniqueId
  
    console.log(data,'提交的数据--------------');
  
    const res = await request.post(
        "/work_ai",
        "/user/image/clip/save",
        data
    );
  
    console.log(res, '提交成功了嘛??');
  
    // 异常了
    if (res?.code && res?.code != 1000) {
      message.error(res?.msg || '提交失败,请稍候重试!')
      throw new Error(res?.msg || '提交失败,请稍候重试!')
    }
    const mainId = res?.id
    router.push({
      name: 'GraphicTextCutPreview',
      query: {
        mainId,
      },
    })
    
  } finally {
  state.submit_loading = false
  }

}

onUnmounted(() => {
  // 清空数据
  store.commit('GraphicTextMixCut/INIT_GRAPHICTEXT_DATA', null)
})

</script>

<template>
  <!-- v-if="!GraphicTextMixCutData" -->
    <div class="note_data" v-if="state.is_loading">
      <div class="loding_content">
        <LoadingOutlined class="loding_icon"></LoadingOutlined>
          <span class="loding_tips">加载中...</span>
      </div>
    </div>

    <div class="GraphicTextMontage">
        <GraphicTextCutNavBack
        ref="GraphicTextCutNavBackRef"
          :leftConfig="{
            isShow: true,
          }"
          :contentConfig="{
            isShow: true,
          }"
          :rightConfig="{
            isShow: true,
          }"
          @backClick="backClick"
        >
          <!-- 头部中间可编辑文本 -->
          <template #content_text>
            <EditableHead
              :titleText="title"
              @changeTitle="title = $event"
            ></EditableHead>
            <!-- 阿里的页面 -->
          </template>
          <template #right_btns>
            <div class="right_btns">
              <!-- 保存图文剪辑项目 -->
              <a-button
                style="font-size: 13px; border-radius: 5px"
                type="default"
                @click="handleSaveProject"
                :loading="state.submit_loading"
                >
                保存图文剪辑项目
              </a-button>
              <a-button
                style="font-size: 13px; border-radius: 5px"
                type="primary"
                @click="previewHandle"
                :loading="state.submit_loading"
                >
                视频图文剪辑预览
              </a-button>
            </div>
          </template>
        </GraphicTextCutNavBack>

        <div class="content_main">

            <div class="content-lf">
              <div class="content-lf-header">
                <div class="lf-header-title">
                  <h3 style="font-weight: 600">镜头内容与配置</h3>
                  <p>为各个镜头配置素材、文案、时长等信息</p>
                </div>

              </div>
              <!-- v-model="GraphicTextMixCutData.resource_data" key="id" -->
              <div class="videoGroupCard_box" id="videoGroupCard_box" v-if="GraphicTextMixCutData">
                <Draggable
                  :animation="200"
                  class="video_preview_content"
                  key="id"
                  v-model="GraphicTextMixCutData.resource_data"
                  :forceFallback="true"
                  :scrollSensitivity="100"
                  :scrollSpeed="20"
                  handle=".tongs"
                  :emptyInsertThreshold="5"
                  :bubbleScroll="false"
                  direction="vertical"
                >
                  <template #item="{ element, index }">
                    <div>
                      <GraphicTextCardList
                        :key="element.id"
                        @updateName="updateName($event, element)"
                        @deletItemData="deletItemData(index)"
                        :targetIndex="index"
                        :itemData="{ ...element }"
                        :explableData="explableData"
                        :ai_requestData="ai_requestData"
                      >
                        <template #default>
                          <div class="tongs" id="tongs">
                            <HolderOutlined />
                          </div>
                        </template>
                      </GraphicTextCardList>
                    </div>
                  </template>
                </Draggable>
                <a-button
                  size="large"
                  style="width: 100%; margin-bottom: 54px; font-size: 13px"
                  @click="addVideoGroupHandle"
                  ><plus-outlined />新增场景</a-button
                >
              </div>
            </div>

            <div class="content-rg">
              <div class="content-rg-title">
                <h3 style="font-weight: 600">
                  配置预览
                  <a-tooltip>
                    <template #title>
                      {{
                        tip ||
                        "这是结合配置模拟的效果，暂未涉及图文剪辑&智能算法，请点击「图文剪辑预览」，生成更贴近成片的预览"
                      }}
                    </template>
                    <exclamation-circle-outlined
                      style="margin-left: 3px; color: #737a87"
                    />
                  </a-tooltip>
                </h3>
                <p style="color: #737a87">查看配置效果</p>
              </div>
              <div class="content-rg-context">
                <template v-if="!state.previewIng">
                  <div class="preview_box" @click="toPreview">
                    <!-- <a-button @click="toPreview" type="primary">生成预览</a-button> -->
                     <div class="to_view_box">
                       <h2 class="to_view_text">请点击查看</h2>
                       <h2 class="to_view_text">模拟效果</h2>
                     </div>
                  </div>
                </template>

                <template v-else>
                  <!-- swiper组件 -->
                  <!-- swiper组件 -->
                     <ViewSwiper style="height: 100%; max-height: 700px;" ref="ViewSwiperRef"></ViewSwiper>
                </template>
              </div> 
            </div>


        </div>

    </div>
</template>


<style lang="less" scoped>

// 加载中 模态框
.note_data{
  position: fixed;
  left: 0;
  top: 0;
  width: 100vw;
  height: 100vh;
  background-color: rgba(0, 0, 0, 0.45);
  z-index: 2;

  display: flex;
  justify-content: center;
  align-items: center;
  .loding_content{
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    gap: 10px;
    color: #fff;
    .loding_tips{
      font-size: 20px;
      font-weight: bold;
    }
    .loding_icon{
      font-size: 30px;

    }
  }
}

.GraphicTextMontage{
    height: 100vh;
    width: 100%;
    overflow: hidden;
    display: flex;
    flex-direction: column;

// 头部左侧样式
  .right_btns {
    font-size: 14px;
    display: flex;
    align-items: center;
    gap: 10px;

    .guide_box {
      color: #4e5969;
      display: flex;
      align-items: center;
      cursor: pointer;

      span {
        margin-left: 6px;
      }
    }
  }

// 下方主要内容部分

.content_main{
    flex: 1;
    // height: calc(100% - 600px);
    display: flex;
    overflow: hidden;

.content-lf {
    flex: 1;
    display: flex;
    flex-direction: column;
    min-width: 650px;
    border-right: 1px solid #f3f3f3;

    .content-lf-header {
        padding: 24px 32px;
        height: 98px;
        display: flex;
        align-items: center;
        justify-content: space-between;
    }

    .lf-header-btn-group {
        display: flex;
        justify-content: space-between;
        align-items: center;
        height: 40px;
        gap: 10px;

        .ai_plot {
        margin-right: 15px;
        display: flex;
        gap: 5px;

        .trigger_span {
            cursor: pointer;
        }
        }
    }

    .videoGroupCard_box {
        flex: 1;
        overflow-y: scroll;
        padding: 0 32px;

        &::-webkit-scrollbar {
        width: 8px;
        /* 滚动条的宽度 */
        height: 10px;
        /* 滚动条的高度，垂直滚动条可能用得上 */
        }

        &::-webkit-scrollbar-thumb {
        background: #cecece;
        /* 滑块的背景颜色 */
        border-radius: 10px;
        /* 滑块的圆角 */
        }

        .tongs {
        cursor: grab;
        display: inline-block;
        transform: translate(-20px, 20px);
        // float: left;
        position: absolute;
        left: 23px;
        top: 12px;

        &:hover {
            background-color: #f1f1f1;
        }
        }
    }
    }

    .content-rg {
    // width: 360px;
    height: 100%;
   // padding: 24px 28px 90px 32px;
   background: #f6f8fa;
    padding: 30px;

    display: flex;
    // justify-content: center;
    // align-items: center;
    flex-direction: column;

    .content-rg-context {
      margin: 0 auto;
        height: 100%;
        width: 360px;
        padding-bottom: 24px;

        .preview_box{
          height: 100%;
          max-height: 700px;
          display: flex;
          justify-content: center;
          align-items: center;
          // background-color: rgb(236, 236, 236);
          background-color: #000;
          border-radius: 15px ;
          cursor: pointer;

          .to_view_box{
            text-align: center;
            .to_view_text{
              font-size: 24px;
              color: #fff;
              margin: 0;
            }
          }

      }
    }
    }

}

}
</style>